<template>
  <div id="picture-detail-page">
    <a-spin :spinning="loading">
      <a-row :gutter="[24, 24]">
        <a-col :span="24">
          <a-card :bordered="false" class="main-card">
            <template #title>
              <a-flex justify="space-between" align="center">
                <a-space>
                  <h3 class="page-title">图片详情</h3>
                  <a-tag v-if="picture.reviewStatus === 0" color="warning">待审核</a-tag>
                  <a-tag v-else-if="picture.reviewStatus === 1" color="success">已通过</a-tag>
                  <a-tag v-else-if="picture.reviewStatus === 2" color="error">已拒绝</a-tag>
                </a-space>
                <a-space>
                  <a-tooltip title="访问次数">
                    <a-button :icon="h(UserAddOutlined)" type="text">
                      {{ formatLargeNumber(visitCount) }}
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="浏览次数">
                    <a-button :icon="h(EyeOutlined)" type="text">
                      {{ formatLargeNumber(viewCount) }}
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="评论总数">
                    <a-button :icon="h(CommentOutlined)" type="text"> {{ commentCount }}</a-button>
                  </a-tooltip>
                  <a-tooltip title="图片详细信息">
                    <a-button type="text" @click="showInfoModal = true">
                      <InfoCircleOutlined style="font-size: 20px; color: #1890ff" />
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="返回">
                    <a-button :icon="h(StepBackwardOutlined)" @click="router.back()"></a-button>
                  </a-tooltip>
                </a-space>
              </a-flex>
            </template>
            <div class="content-wrapper">
              <div class="image-container">
                <a-image
                  :src="picture.url"
                  :alt="picture.name"
                  :preview="true"
                  class="main-image"
                />
              </div>
              <div class="info-container">
                <div class="title-section">
                  <a-typography-title :level="3" :ellipsis="{ rows: 1 }" class="picture-title">
                    {{ picture.name || '未命名图片' }}
                  </a-typography-title>
                  <div class="meta-info">
                    <a-space>
                      <a-tag color="blue">{{ picture.category || '未分类' }}</a-tag>
                      <span class="upload-time"
                        >上传于 {{ dayjs(picture.createTime).format('YYYY-MM-DD') }}</span
                      >
                    </a-space>
                  </div>
                </div>
                <a-typography-paragraph
                  class="introduction"
                  :ellipsis="{ rows: 3, expandable: true, symbol: '展开' }"
                  :copyable="{
                    text: picture.introduction || '暂无简介',
                    tooltips: ['复制', '已复制'],
                    onCopy: () => message.success('复制成功'),
                  }"
                >
                  {{ picture.introduction || '暂无简介' }}
                </a-typography-paragraph>
                <div class="tags-section">
                  <a-space wrap>
                    <a-tag v-for="tag in picture.tags" :key="tag" color="blue">{{ tag }}</a-tag>
                  </a-space>
                </div>
              </div>
            </div>
            <div class="action-bar">
              <a-space>
                <a-button
                  :icon="h(LikeOutlined)"
                  :type="picture.isLike ? 'primary' : 'default'"
                  @click="handleThumbPicture"
                  :loading="thumbLoading"
                >
                  {{ picture.isLike ? '已点赞' : '点赞' }} {{ picture.likeCount ?? 0 }}
                </a-button>
                <a-popover
                  title="点赞用户"
                  trigger="click"
                  placement="bottom"
                  :overlayStyle="{ width: '300px' }"
                >
                  <template #content>
                    <div class="thumb-users">
                      <a-list
                        :data-source="allThumbUsers"
                        :grid="{ gutter: 16, column: 4 }"
                        :pagination="false"
                      >
                        <template #renderItem="{ item }">
                          <a-list-item>
                            <a-tooltip :title="item.userName">
                              <a-avatar
                                :src="item.userAvatar"
                                size="large"
                                @click="router.push(`/user/detail/${item.id}`)"
                                :style="{ cursor: 'pointer' }"
                              />
                            </a-tooltip>
                          </a-list-item>
                        </template>
                      </a-list>
                    </div>
                  </template>
                  <a-avatar-group
                    :max-count="5"
                    max-popover-trigger="click"
                    size="large"
                    :max-style="{ color: '#f56a00', backgroundColor: '#fde3cf', cursor: 'pointer' }"
                  >
                    <a-tooltip v-for="user in allThumbUsers" :key="user.id" :title="user.userName">
                      <a-avatar
                        :src="user.userAvatar"
                        size="large"
                        @click="router.push(`/user/detail/${user.id}`)"
                        :style="{ cursor: 'pointer' }"
                      />
                    </a-tooltip>
                  </a-avatar-group>
                </a-popover>
                <a-button type="text" class="comment-btn" @click="showComment = !showComment">
                  <CommentOutlined style="font-size: 24px; color: #1890ff" />
                  <span v-if="commentCount > 0" class="comment-count">{{ commentCount }}</span>
                </a-button>
              </a-space>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </a-spin>

    <!-- 图片详情弹框 -->
    <a-modal
      v-model:open="showInfoModal"
      title="图片详情"
      width="600px"
      :footer="null"
      @cancel="showInfoModal = false"
    >
      <a-descriptions :column="1" size="small">
        <a-descriptions-item label="作者">
          <a-space>
            <a-space @click="router.push(`/user/detail/${picture.userId}`)" class="author-info">
              <a-avatar :src="picture.user?.userAvatar ?? '-'"></a-avatar>
              <a-tag color="green">{{ picture.user?.userName }}</a-tag>
            </a-space>
            <a-space v-if="picture.userId !== userStore.userInfo?.id && userStore.isLogin">
              <a-button v-if="!isFollow" @click="handleFollow" :loading="followLoading"
                >关注</a-button
              >
              <a-button v-else @click="handleFollow" danger :loading="followLoading">取关</a-button>
            </a-space>
          </a-space>
        </a-descriptions-item>
        <a-descriptions-item label="名称">{{ picture.name || '-' }}</a-descriptions-item>
        <a-descriptions-item label="简介">{{ picture.introduction || '-' }}</a-descriptions-item>
        <a-descriptions-item label="分类">{{ picture.category || '-' }}</a-descriptions-item>
        <a-descriptions-item label="标签">
          <a-space wrap>
            <a-tag v-for="tag in picture.tags" :key="tag" color="blue">{{ tag }}</a-tag>
          </a-space>
        </a-descriptions-item>
        <a-descriptions-item label="格式">{{ picture.picFormat || '-' }}</a-descriptions-item>
        <a-descriptions-item label="尺寸"
          >{{ picture.picWidth }}x{{ picture.picHeight }}</a-descriptions-item
        >
        <a-descriptions-item label="宽高比">{{ picture.picScale || '-' }}</a-descriptions-item>
        <a-descriptions-item label="大小">{{ formatSize(picture.picSize) }}</a-descriptions-item>
        <a-descriptions-item label="主色调">
          <div class="color-preview" :style="{ backgroundColor: picture.picColor }"></div>
          <span>{{ picture.picColor || '-' }}</span>
        </a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-space v-if="userStore.isLogin" class="action-buttons">
        <a-tooltip title="下载图片">
          <a-button type="primary" @click="handleDownload" :loading="downloadLoading">
            <template #icon><DownloadOutlined /></template>
            下载
          </a-button>
        </a-tooltip>

        <a-tooltip title="上传到私人空间">
          <a-button @click="handleAddToSpace" :loading="addToSpaceLoading">
            <template #icon><UploadOutlined /></template>
            收藏
          </a-button>
        </a-tooltip>

        <a-tooltip title="分享图片">
          <a-button @click="handleShare">
            <template #icon><ShareAltOutlined /></template>
            分享
          </a-button>
        </a-tooltip>

        <template v-if="canEditPicture">
          <a-tooltip title="编辑图片">
            <a-button type="ghost" @click="handleEdit">
              <template #icon><EditOutlined /></template>
              编辑
            </a-button>
          </a-tooltip>
        </template>

        <template v-if="canDeletePicture">
          <a-tooltip title="删除图片">
            <a-popconfirm
              title="确定要删除这张图片吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete"
            >
              <a-button danger>
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-space>
    </a-modal>

    <PictureCommentPage
      v-if="picture.id"
      :picture-id="String(picture.id)"
      v-model:comment-count="commentCount"
      v-model:show="showComment"
    />

    <ShareModal v-model="openShareModal" title="分享图片" :share-url="shareUrl" />
  </div>
</template>

<script setup lang="ts">
import {
  countPictureViewUsingGet,
  countPictureVisitUsingGet,
  deletePictureUsingPost,
  doThumbPictureUsingPost,
  getPictureVoByIdUsingGet,
  getTop5ThumbUserByPictureIdUsingGet,
} from '@/api/pictureController.ts'
import { followUserUsingPost, isFollowUserUsingGet } from '@/api/userController.ts'
import ShareModal from '@/components/ShareModal.vue'
import { SPACE_PERMISSION_ENUM } from '@/constants/space.ts'
import { useUserStore } from '@/stores/user.ts'
import { downloadImage, formatSize } from '@/utils'
import { doAddPicture } from '@/utils/picture.ts'
import PictureCommentPage from '@/views/picture/PictureCommentPage.vue'
import {
  CloseOutlined,
  CommentOutlined,
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  EyeOutlined,
  LikeOutlined,
  MenuOutlined,
  ShareAltOutlined,
  StepBackwardOutlined,
  UploadOutlined,
  UserAddOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons-vue'
import { useWindowSize } from '@vueuse/core'
import { message } from 'ant-design-vue'
import { computed, h, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'

const userStore = useUserStore()
const router = useRouter()

// 状态管理
const loading = ref<boolean>(false)
const thumbLoading = ref<boolean>(false)
const followLoading = ref<boolean>(false)
const downloadLoading = ref<boolean>(false)
const addToSpaceLoading = ref<boolean>(false)
const open = ref<boolean>(false)
const shareUrl = ref<string>('')
const commentCount = ref<number>(0)
const isFollow = ref<boolean>(false)
const visitCount = ref<number>(0)
const viewCount = ref<number>(0)
const picture = ref<API.PictureVO>({})
const allThumbUsers = ref<API.UserVO[]>([])
const showInfoModal = ref<boolean>(false)
const showComment = ref(false)

interface Props {
  id: string
}

const props = defineProps<Props>()

// 权限检查
const canEditPicture = computed(() => {
  return (picture.value.permissionList ?? []).includes(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
})

const canDeletePicture = computed(() => {
  return (picture.value.permissionList ?? []).includes(SPACE_PERMISSION_ENUM.PICTURE_DELETE)
})

// 响应式窗口大小
const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

// 监听窗口大小变化，自动处理信息面板显示
watch(width, (newWidth) => {
  if (newWidth < 768) {
    showInfoModal.value = false
  }
})

// 获取图片详情
const getPicture = async () => {
  if (!props.id) {
    message.error('图片ID不能为空')
    return
  }
  const pictureId = props.id
  loading.value = true
  try {
    const res = await getPictureVoByIdUsingGet({
      id: pictureId,
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error(res.data.message || '获取图片详情失败')
    }
  } catch (error: any) {
    console.error('获取图片详情失败:', error)
    if (error.response) {
      switch (error.response.status) {
        case 401:
          message.error('请先登录')
          break
        case 403:
          message.error('没有访问权限')
          break
        case 404:
          message.error('图片不存在')
          break
        default:
          message.error(error.response.data?.message || '获取图片详情失败')
      }
    } else {
      message.error('网络错误，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 点赞操作
const handleThumbPicture = async () => {
  if (!picture.value.id) return
  thumbLoading.value = true
  try {
    const res = await doThumbPictureUsingPost({
      id: picture.value.id,
    })
    if (res.data.code === 0 && res.data.data) {
      await getPicture()
      await getAllThumbUsers()
      message.success(picture.value.isLike ? '取消点赞成功' : '点赞成功')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    message.error('操作失败')
  } finally {
    thumbLoading.value = false
  }
}

// 获取点赞用户
const getAllThumbUsers = async () => {
  try {
    const res = await getTop5ThumbUserByPictureIdUsingGet({
      pictureId: props.id,
      limit: 49,
    })
    if (res.data.code === 0 && res.data.data) {
      allThumbUsers.value = res.data.data
    }
  } catch (error) {
    console.error('获取点赞用户失败:', error)
  }
}

// 关注操作
const handleFollow = async () => {
  if (!picture.value.userId) return
  followLoading.value = true
  try {
    const res = await followUserUsingPost({
      followedUserId: picture.value.userId,
      isFollow: isFollow.value,
    })
    if (res.data.code === 0) {
      await checkFollow()
      message.success(isFollow.value ? '取关成功' : '关注成功')
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    message.error('操作失败')
  } finally {
    followLoading.value = false
  }
}

// 检查关注状态
const checkFollow = async () => {
  if (!picture.value.userId) return
  try {
    const res = await isFollowUserUsingGet({
      followedUserId: picture.value.userId,
    })
    if (res.data.code === 0) {
      isFollow.value = res.data.data ?? false
    }
  } catch (error) {
    console.error('检查关注状态失败:', error)
  }
}

// 统计访问次数
const getVisitCount = async () => {
  try {
    const res = await countPictureVisitUsingGet({
      pictureId: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      // 使用BigInt处理大数字
      const count = BigInt(res.data.data)
      visitCount.value = Number(count)
    }
  } catch (error) {
    console.error('获取访问次数失败:', error)
  }
}

// 统计浏览次数
const getViewCount = async () => {
  try {
    const res = await countPictureViewUsingGet({
      pictureId: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      // 使用BigInt处理大数字
      const count = BigInt(res.data.data)
      viewCount.value = Number(count)
    }
  } catch (error) {
    console.error('获取浏览次数失败:', error)
  }
}

// 格式化大数字
const formatLargeNumber = (num: number | bigint): string => {
  if (typeof num === 'bigint') {
    return num.toString()
  }
  if (num >= 1e12) {
    return (num / 1e12).toFixed(2) + 'T'
  }
  if (num >= 1e9) {
    return (num / 1e9).toFixed(2) + 'B'
  }
  if (num >= 1e6) {
    return (num / 1e6).toFixed(2) + 'M'
  }
  if (num >= 1e3) {
    return (num / 1e3).toFixed(2) + 'K'
  }
  return num.toString()
}

// 下载图片
const handleDownload = async () => {
  if (!picture.value.url || !picture.value.name) return
  downloadLoading.value = true
  try {
    await downloadImage(picture.value.url, picture.value.name)
    message.success('下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    message.error('下载失败')
  } finally {
    downloadLoading.value = false
  }
}

// 添加到空间
const handleAddToSpace = async () => {
  if (!picture.value.originalUrl || !picture.value.name) return
  addToSpaceLoading.value = true
  try {
    await doAddPicture(picture.value.originalUrl, picture.value.name)
    message.success('添加成功')
    await router.push('/space/my')
  } catch (error) {
    console.error('添加到空间失败:', error)
    message.error('添加失败')
  } finally {
    addToSpaceLoading.value = false
  }
}

// 分享图片
const openShareModal = ref<boolean>(false)
const handleShare = () => {
  shareUrl.value = window.location.href
  openShareModal.value = true
}

// 编辑图片
const handleEdit = () => {
  router.push({
    path: '/picture/add',
    query: {
      id: picture.value?.id,
      spaceId: picture.value?.spaceId,
    },
  })
}

// 删除图片
const handleDelete = async () => {
  if (!picture.value.id) return
  try {
    const res = await deletePictureUsingPost({ id: picture.value.id })
    if (res.data.code === 0) {
      message.success('删除成功')
      router.push('/')
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

onMounted(async () => {
  await getPicture()
  await getAllThumbUsers()
  await checkFollow()
  getVisitCount()
  getViewCount()
})
</script>

<style lang="scss" scoped>
#picture-detail-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;

  .main-card {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .content-wrapper {
    display: flex;
    flex-direction: column;
    gap: 24px;
    margin-bottom: 24px;

    @media screen and (min-width: 768px) {
      flex-direction: row;
      align-items: flex-start;
    }

    .image-container {
      flex: 1;
      min-width: 0;
      aspect-ratio: 1;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      background: #fff;

      .main-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .info-container {
      flex: 1;
      min-width: 0;
      padding: 16px;
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      .title-section {
        margin-bottom: 16px;

        .picture-title {
          margin: 0 0 8px;
          font-size: 24px;
          font-weight: 600;
          color: #1f1f1f;
        }

        .meta-info {
          .upload-time {
            color: #999;
            font-size: 14px;
          }
        }
      }

      .introduction {
        font-size: 15px;
        line-height: 1.6;
        color: #333;
        margin: 16px 0;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 8px;
        border: 1px solid #f0f0f0;

        :deep(.ant-typography-copy) {
          color: #1890ff;
          margin-left: 8px;

          &:hover {
            color: #40a9ff;
          }
        }
      }

      .tags-section {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #f0f0f0;
      }
    }
  }

  .action-bar {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .comment-btn {
      position: relative;
      padding: 4px 8px;
      height: auto;
      display: flex;
      align-items: center;
      transition: all 0.3s;

      &:hover {
        background: rgba(24, 144, 255, 0.1);
      }

      .comment-count {
        position: absolute;
        top: -8px;
        right: -8px;
        background: #ff4d4f;
        color: white;
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 10px;
        min-width: 20px;
        text-align: center;
      }
    }
  }
}

// 弹框样式
:deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;

  .ant-modal-header {
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 24px;
  }

  .ant-modal-body {
    padding: 24px;
  }
}

// 响应式优化
@media screen and (max-width: 768px) {
  #picture-detail-page {
    padding: 12px;

    .content-wrapper {
      .info-container {
        margin-top: 16px;
      }
    }

    .action-bar {
      flex-direction: column;
      gap: 16px;
    }
  }
}
</style>
